import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import { VueAxios } from './axios'

import { getToken } from '@/utils/auth'
import { tansParams } from '@/utils'
import store from '@/store'
// import cache from '@/utils/cache'
import { showLoading, hideLoading } from '@/utils/requestLoading'
let configChace = null // 存放请求参数，在进入错误时候也关掉loading
// let baseURL = process.env.VUE_APP_API_BASE_URL
// const initRequest = ({ requestBase = '' }) => {
//   baseURL = requestBase + process.env.VUE_APP_PUBLIC_PATH + process.env.VUE_APP_API_BASE_URL
// }
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60 * 1000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    if (config.headers?.showLoading) {
      showLoading()
      configChace = config
    }
    // if (!getToken()) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params)
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    // if (config.method === 'post' || config.method === 'put') {
    //   const requestObj = {
    //     url: config.url,
    //     data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
    //     time: new Date().getTime()
    //   }
    //   const sessionObj = cache.session.getJSON('sessionObj')
    //   if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
    //     cache.session.setJSON('sessionObj', requestObj)
    //   } else {
    //     const sUrl = sessionObj.url // 请求地址
    //     const sData = sessionObj.data // 请求数据
    //     const sTime = sessionObj.time // 请求时间
    //     const interval = 1000 // 间隔时间(ms)，小于此时间视为重复提交
    //     if (sData === requestObj.data && requestObj.time - sTime < interval && sUrl === requestObj.url) {
    //       const message = '数据正在处理，请勿重复提交'
    //       console.warn(`[${sUrl}]: ` + message)
    //       return
    //     } else {
    //       cache.session.setJSON('sessionObj', requestObj)
    //       return config
    //     }
    //   }
    // }
    return config
  },
  (error) => {
    // do something with request error
    if (configChace?.headers?.showLoading) {
      hideLoading()
      configChace = null
    }
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (
      response.headers['content-type'] === 'application/octet-stream' ||
      response.headers['content-type']?.indexOf('application/vnd.ms-excel') !== -1 ||
      response.config['responseType'] === 'blob'
    ) {
      return {
        res: response.data
      }
    }

    // 判断当前请求是否设置了不显示Loading（不显示自然无需隐藏）
    if (response.config?.headers?.showLoading) {
      hideLoading()
    }
    if (response.status === 200 && response.data.code !== 'success') {
      Message({
        message: response.data.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(response.message || 'Error'))
    }
    if (response.status !== 200) {
       if (response.status === 401) {
        MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          alert('退出登录')
        })
      }
      Message({
        message: response.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(response.message || 'Error'))
    } else {
      return response.data
    }
  },
  (error) => {
    // 关闭loading
    if (configChace?.headers?.showLoading) {
      hideLoading()
      configChace = null
    }
    if (error.response.status === 401) {
      return MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/logout')
      })
    } else {
      Message({
        message: error.response.data.msg || error,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)
const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}
export default service
export { installer as VueAxios, service as axios }
